package com.zhongan.util;

import com.alibaba.fastjson.JSON;
import com.zhongan.constants.Constant;
import com.zhongan.dto.ApiFinalResponse;
import com.zhongan.dto.ApiRequest;
import com.zhongan.dto.ApiResponse;

import java.text.MessageFormat;

/**
 * 简单字符串处理
 * 
 * @author kevin
 * 
 */
public class SimpleStringUtil {
	public static String replaceHtml(String text) {
		text = text.replaceAll("\\<", "&lt;");
		text = text.replaceAll("\\>", "&gt;");
		return text;
	}

	public static String replaceHtmlBr(String text) {
		text = text.replaceAll("\n", "<br>");
		return text;
	}

	/**
	 * 统一请求相应数据
	 *
	 * @param apiReq
	 * @param apiRsp
	 * @param msgArgs
	 * @return
	 */
	public static String buildResponse(ApiRequest apiReq, ApiResponse apiRsp, Object... msgArgs) {
		ApiFinalResponse finalRsp = new ApiFinalResponse();
		finalRsp.setIsSuccess(apiRsp.getReturnEnum().getIsSuccess());
		finalRsp.setCode(apiRsp.getReturnEnum().getCode());
		if (msgArgs != null && msgArgs.length > 0) {
			finalRsp.setMsg(MessageFormat.format(apiRsp.getReturnEnum().getMsg(), msgArgs));
		} else {
			finalRsp.setMsg(apiRsp.getReturnEnum().getMsg());
		}
		finalRsp.setCount(apiRsp.getCount());
		finalRsp.setResults(apiRsp.getResults());
		if (apiRsp.getCount() != null && StringUtil.isNotEmpty(apiReq.get(Constant.PAGE_SIZE)) && RegexUtil.isPositiveInteger(apiReq.get(Constant.PAGE_SIZE).toString())) {
			int pageSize = apiReq.getInt(Constant.PAGE_SIZE);
			int page = 1;
			if (StringUtil.isNotEmpty(apiReq.get(Constant.PAGE)) && RegexUtil.isPositiveInteger(apiReq.get(Constant.PAGE).toString())) {
				page = apiReq.getInt(Constant.PAGE);
			}
			int totalPages = apiRsp.getCount() / pageSize;
			if (apiRsp.getCount() % pageSize > 0) {
				totalPages++;
			}
			finalRsp.setTotalPages(totalPages);
			finalRsp.setCurPage(page);
			finalRsp.setPageSize(pageSize);
		}
		return JSON.toJSONString(finalRsp);
	}

	public static void main(String[] a) {
		String text = "回家看看厉害吧[e_183][e_184][e_191][e_190][e_198]";
		text = replaceHtml("<script>alert(11);</script>");
		System.out.println(text);
	}
}
